<?php


namespace Bxy\Jwt\middleware;

use Bxy\Jwt\AuthInterface;
use Bxy\Jwt\method\JwtHeader;
use Bxy\Jwt\TraitBxyAuth;
use FastRoute\Dispatcher;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JWTAuthMiddleware  implements MiddlewareInterface
{
    use TraitBxyAuth;
    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // TODO: Implement process() method.
        $dispatched = $request->getAttribute(Dispatched::class);
        if ($dispatched->status !== Dispatcher::FOUND) {
            return $handler->handle($request);
        }
        [$isPublic, $isWhitelist,$isCheck] = $this->checkRouter($request, $dispatched);
        if($isCheck==true || $isPublic==true || $isWhitelist==true){
            $authenticator = make(JwtHeader::class);
            if (!$authenticator instanceof AuthInterface) {
                throw new \RuntimeException(get_class($authenticator) . ' must implement ' . AuthInterface::class);
            }
            $authenticator->authenticate($request,$isPublic,$isWhitelist,$isCheck);
        }
        return  $handler->handle($request);
    }
}
